<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>我的订单</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .container {
            max-width: 1200px;
            margin-left: 300px;
            padding: 20px;
            background: white;
            min-height: calc(100vh - 40px);
        }
        .order-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .order-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .order-detail-btn {
            background: #2196F3;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
        }
        .order-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1050;
        }
        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 800px;
        }
        .close-modal {
            background: #ff5252;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 15px;
        }
        .payment-section {
            margin: 15px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .payment-info {
            margin: 15px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        #pay-btn {
            width: 100%;
        }
    </style>
</head>
<body data-user-role="customer">
<div th:replace="~{common/enhanced-global-notification :: notification}"></div>

<div th:replace="~{common/customer-navbar :: navbar}"></div>

    <div class="container">
        <h1>我的订单</h1>
        <div id="orders-list">
            <div class="order-card" th:each="order : ${orders}">
                <div class="order-header">
                    <span th:text="'订单号: '+${order.orderId}">订单号</span>
                    <span th:text="'状态: '+${order.status}">状态</span>
                </div>
                <div class="order-details">
                    <p th:text="'总价: ¥'+${#numbers.formatDecimal(order.totalPrice, 1, 2)}">总价</p>
                    <p th:text="'创建时间: '+${order.date}">日期</p>
                </div>
                <button class="order-detail-btn" th:attr="data-id=${order.orderId}">查看详情</button>
            </div>
        </div>
    </div>

    <div id="order-modal" class="order-modal" style="display: none;">
        <div class="modal-content">
            <div id="modal-content-inner"></div>
            <button class="btn btn-secondary mt-3" onclick="closeModal()">关闭</button>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定查看详情按钮事件
            document.querySelectorAll('.order-detail-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const orderId = this.getAttribute('data-id');
                    fetchOrderDetails(orderId);
                });
            });
        });

        function fetchOrderDetails(orderId) {
            fetch(`/api/orders/detail/${orderId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('API返回数据:', data);
                    if (data) {
                        // 直接返回订单对象的情况
                        if (data.orderId) {
                            showOrderDetailModal(data);
                        }
                        // 包含success字段的标准响应
                        else if (data.success && data.order) {
                            showOrderDetailModal(data.order);
                        }
                        // 其他情况
                        else {
                            const errorMsg = data.message || '未知错误';
                            console.error('API返回格式异常:', data);
                            alert(`获取订单详情失败: ${errorMsg}`);
                        }
                    } else {
                        console.error('API返回空数据');
                        alert('获取订单详情失败: 服务器返回空数据');
                    }
                })
                .catch(error => {
                    console.error('获取订单详情失败:', error);
                    alert(`获取订单详情失败: ${error.message}`);
                });
        }

        function showOrderDetailModal(order) {
            console.log('订单状态:', order.status); // 调试订单状态
            const modalContent = document.getElementById('modal-content-inner');
            modalContent.innerHTML = `
                <h2>订单详情 #${order.orderId}</h2>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <p><strong>状态:</strong> ${order.status}</p>
                        <p><strong>用户ID:</strong> ${order.userId}</p>
                        <p><strong>总价:</strong> ¥${order.totalPrice.toFixed(2)}</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>创建时间:</strong> ${order.date}</p>
                        <p><strong>支付方式:</strong> ${order.paymentType || '未支付'}</p>
                        <p><strong>支付账号:</strong> ${order.paymentAccount || '无'}</p>
                    </div>
                </div>
                <div class="mb-3">
                    <h4>商品列表</h4>
                    <table class="table">
                        <thead>
                            <tr>
                                <th>商品名称</th>
                                <th>单价</th>
                                <th>数量</th>
                                <th>小计</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${order.productBunches ? order.productBunches.map(item => `
                                <tr>
                                    <td>${item.product.productName || '未知商品'}</td>
                                    <td>¥${(item.product.price || 0).toFixed(2)}</td>
                                    <td>${item.quantity || 1}</td>
                                    <td>¥${((item.product.price || 0) * (item.quantity || 1)).toFixed(2)}</td>
                                </tr>
                            `).join('') : '<tr><td colspan="4">暂无商品信息</td></tr>'}
                        </tbody>
                    </table>
                </div>
                ${order.status === '待支付' ? `
                <div class="payment-section">
                    <h3>支付方式</h3>
                    <select id="payment-type" class="form-select mb-2">
                        <option value="">请选择支付方式</option>
                        <option value="支付宝">支付宝</option>
                        <option value="微信支付">微信支付</option>
                        <option value="银行卡">银行卡</option>
                    </select>
                    <input type="text" id="payment-account" class="form-control mb-2" placeholder="支付账号">
                    <div class="d-flex justify-content-between">
                        <button id="pay-btn" class="btn btn-primary">立即支付</button>
                        <button id="cancel-btn" class="btn btn-danger"
                            onclick="cancelOrder('${order.orderId}')">取消订单</button>
                    </div>
                </div>
                ` : `
                <div class="payment-info">
                    <p>支付方式: ${order.paymentType || '未支付'}</p>
                    <p>支付账号: ${order.paymentAccount || '无'}</p>
                </div>
                `}

                ${order.status === '已发货' ? `
                <div class="d-flex justify-content-end mt-3">
                    <button class="btn btn-success" onclick="confirmReceipt('${order.orderId}')">确认收货</button>
                </div>
                ` : ''}

                ${order.status === '待评价' ? `
                <div class="review-section mt-4" data-order-id="${order.orderId}">
                    <h4>商品评价</h4>
                    <div id="review-products-list">
                        ${order.productBunches ?
                            (() => {
                                const distinctProducts = [];
                                const productIdsAdded = new Set();
                                for (const item of order.productBunches) {
                                    if (item.product && !productIdsAdded.has(item.productId)) {
                                        distinctProducts.push(item);
                                        productIdsAdded.add(item.productId);
                                    }
                                }

                                return distinctProducts.map(item => {
                                    const isReviewed = order.reviewedProductIds && order.reviewedProductIds.includes(item.productId);
                                    return `
                                        <div class="card mb-3 product-review-card" data-product-id="${item.productId}">
                                            <div class="card-body">
                                                <h5>${item.product.productName || '未知商品'}</h5>
                                                ${isReviewed ?
                                                    `<div class='alert alert-success'><i class="fas fa-check-circle me-2"></i>已提交评价</div>` :
                                                    `<div class="rating mb-2">
                                                        <span>评分: </span>
                                                        <select id="rating-${item.productId}" class="form-select d-inline-block w-auto">
                                                            <option value="5">5星</option>
                                                            <option value="4">4星</option>
                                                            <option value="3">3星</option>
                                                            <option value="2">2星</option>
                                                            <option value="1">1星</option>
                                                        </select>
                                                    </div>
                                                    <textarea id="comment-${item.productId}" class="form-control mb-2"
                                                        placeholder="请输入评价内容"></textarea>
                                                    <button class="btn btn-primary submit-review-btn"
                                                        data-order-id="${order.orderId}"
                                                        data-product-id="${item.productId}">提交评价</button>`
                                                }
                                            </div>
                                        </div>
                                    `;
                                }).join('');
                            })()
                        : '<p>暂无商品可评价</p>'}
                    </div>
                </div>
                ` : ''}
            `;

            // 添加支付按钮事件
            const payBtn = document.getElementById('pay-btn');
            if (payBtn) {
                payBtn.addEventListener('click', function() {
                    const paymentType = document.getElementById('payment-type').value;
                    const paymentAccount = document.getElementById('payment-account').value;

                    if (!paymentType) {
                        alert('请选择支付方式');
                        return;
                    }

                    fetch(`/api/orders/pay/${order.orderId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            paymentType: paymentType,
                            paymentAccount: paymentAccount
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('支付成功');
                            location.reload();
                        } else {
                            alert('支付失败: ' + data.message);
                        }
                    });
                });
            }

            document.getElementById('order-modal').style.display = 'flex';
            // 绑定提交评价按钮事件
            document.querySelectorAll('.submit-review-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const orderId = this.getAttribute('data-order-id');
                    const productId = this.getAttribute('data-product-id');
                    submitReview(orderId, productId);
                });
            });
        }

        function closeModal() {
            document.getElementById('order-modal').style.display = 'none';
        }

        function cancelOrder(orderId) {
            if (!confirm('确定要取消此订单吗？')) return;

            fetch(`/api/orders/update-status/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    status: '已取消'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('订单已取消');
                    location.reload();
                } else {
                    alert('取消订单失败: ' + data.message);
                }
            });
        }

        function confirmReceipt(orderId) {
            if (!confirm('确认收到商品吗？')) return;

            fetch(`/api/orders/confirm-receipt/${orderId}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('确认收货成功');
                    // 重新获取订单详情并刷新模态框
                    fetchOrderDetails(orderId);
                } else {
                    alert('确认收货失败: ' + data.message);
                }
            });
        }

        function submitReview(orderId, productId) {
            const ratingSelect = document.getElementById(`rating-${productId}`);
            const commentTextarea = document.getElementById(`comment-${productId}`);
            const submitBtn = document.querySelector(`.submit-review-btn[data-product-id="${productId}"]`);

            const rating = ratingSelect ? ratingSelect.value : null;
            const comment = commentTextarea ? commentTextarea.value : '';

            if (!rating || !comment.trim()) {
                alert('请填写完整的评价内容 (评分和评论)');
                return;
            }

            // 禁用按钮并显示加载状态
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 提交中...';
            }

            fetch(`/api/orders/submit-review/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    productId: productId,
                    rating: parseInt(rating),
                    comment: comment
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新当前商品评价区域为“已提交”状态
                    const productReviewCard = document.querySelector(`.product-review-card[data-product-id="${productId}"]`);
                    if (productReviewCard) {
                        productReviewCard.innerHTML = `
                            <div class='card-body'>
                                <h5>${productReviewCard.querySelector('h5').textContent}</h5>
                                <div class='alert alert-success'><i class="fas fa-check-circle me-2"></i>已提交评价</div>
                            </div>
                        `;
                    }

                    alert('评价提交成功！');

                    // 检查是否所有商品都已评价
                    // 重新获取订单详情，后端会根据是否有未评价商品更新 reviewedProductIds 和订单状态
                    fetch(`/api/orders/detail/${orderId}`)
                        .then(res => res.json())
                        .then(updatedOrder => {
                            if (updatedOrder && updatedOrder.orderId) {
                                // 判断是否所有商品都已评价 (根据后端返回的 reviewedProductIds 和 productBunches 数量)
                                const distinctProductsCount = new Set(updatedOrder.productBunches.map(b => b.productId)).size;
                                const reviewedCount = updatedOrder.reviewedProductIds ? updatedOrder.reviewedProductIds.length : 0;

                                if (updatedOrder.status === '已完成' || distinctProductsCount === reviewedCount) {
                                    alert('所有商品都已评价，订单已完成！');
                                    closeModal(); // 关闭模态框
                                    location.reload(); // 刷新页面
                                }
                            }
                        })
                        .catch(error => {
                            console.error('重新获取订单详情失败:', error);
                            // 即使重新获取失败，也至少更新一下页面，可能只是网络问题
                            location.reload();
                        });

                } else {
                    alert('评价提交失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('评价提交失败: ' + error.message);
            })
            .finally(() => {
                // 恢复按钮状态（如果未关闭模态框或刷新页面）
                if (submitBtn && !submitBtn.disabled) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '提交评价';
                }
            });
        }
    </script>
</body>
</html>